package com.bigdata.bookinfo.reduce;

import com.bigdata.bookinfo.pojo.KeyAndScore;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class CommentMaxReduce extends Reducer<Text, KeyAndScore, Text, Text> {

    @Override
    protected void reduce(Text key, Iterable<KeyAndScore> values, Context context) throws IOException, InterruptedException {
        List<KeyAndScore> list = new ArrayList<>();
        for (KeyAndScore keyAndScore : values) {
            list.add(new KeyAndScore(keyAndScore.getKey(),keyAndScore.getScore()));
        }
        for (int i = 0; i < 10; i++) {
            System.out.println(list.get(i));
        }
        list.sort((o1, o2) -> {
            if (o2.getScore() == o1.getScore()) {
                return 0;
            }
            return o2.getScore()>o1.getScore()?1:-1;
        });
        for (int i = 0; i < 10; i++) {
            System.out.println(list.get(i));
        }
        if(list.size()<10){
            for (KeyAndScore keyAndScore : list) {
                context.write(new Text(keyAndScore.getKey()),new Text(keyAndScore.getScore()+""));
            }
            return;
        }
        for (int i = 0; i < 10; i++) {
            context.write(new Text(list.get(i).getKey()),new Text(list.get(i).getScore()+""));
        }
    }
}
